using System;
using System.Collections.Generic;
using System.Text;

using SBPweb.Modules.Modularity;

namespace SBPweb.Contracts.Implementation
{
	/// <summary>
	/// Class of Layout
	/// </summary>
	public class Layout : IPersistable
	{
		#region Private members

		private IPersistable pParentPersistable;
		private IStatePersistenceService pPersistenceService;
		private string pName;
		private string pLayout;
		private PersistableDictionary pModules;

		#endregion

		#region Constructor logic

		/// <summary>
		/// Constructor of Layout
		/// </summary>
		/// <param name="parent">parent</param>
		/// <param name="persistenceService">persistence service</param>
		/// <param name="name">name</param>
		/// <param name="layout">layout</param>
		public Layout(IPersistable parent, IStatePersistenceService persistenceService, string name, string layout)
		{
			pParentPersistable = parent;
			pPersistenceService = persistenceService;
			pName = name;
			pLayout = layout;
			pModules = new PersistableDictionary("Modules", this, pPersistenceService);
		}

		#endregion

		#region Public properties

		/// <summary>
		/// Returns parent as persistable
		/// </summary>
		public IPersistable ParentPersistable
		{
			get 
			{
				return pParentPersistable;
			} 
		}

		/// <summary>
		/// Persistency key
		/// </summary>
		public string PersistencyKey
		{
			get
			{
				return string.Format("{0} - {1}", this.GetType().Name, pName); ;
			}
		}

		/// <summary>
		/// Name
		/// </summary>
		public string Name
		{
			get
			{
				return pName;
			}
			internal set
			{
				pName = value;
			}
		}

		/// <summary>
		/// Layout string
		/// </summary>
		public string LayoutString
		{
			get
			{
				return pLayout;
			}
			internal set
			{
				pLayout = value;
			}
		}

		/// <summary>
		/// Modules
		/// </summary>
		public PersistableDictionary Modules
		{
			get
			{
				return pModules;
			}
		}

		#endregion

		#region Public methods

		/// <summary>
		/// Load persistency
		/// </summary>
		public void LoadPersistency()
		{
			if (pPersistenceService != null)
			{
				PersistencyDictionary state = pPersistenceService.Load(this);
				pLayout = state.GetString("Layout", string.Empty);
				pModules.LoadPersistency();
			}
		}

		/// <summary>
		/// Save persistency
		/// </summary>
		public void SavePersistency()
		{
			if (pPersistenceService != null)
			{
				PersistencyDictionary state = pPersistenceService.Load(this);
				state.SetString("Layout", pLayout);
				pPersistenceService.Save(this, state);
				pModules.SavePersistency();
			}
		}

		#endregion
	}
}
